// Copyright 2019 The rhyme_lph Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// q [author] rhyme_lph
// I [email]  rhymelph@gmail.com
// Z [github] https://github.com/rhymelph

import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/generated/l10n.dart';
import 'package:finance_app/src/common/app_spaces.dart';
import 'package:finance_app/src/common/config.dart';
import 'package:finance_app/src/entities/ocr_attachment_entity.dart';
import 'package:finance_app/src/entities/services_entity.dart';
import 'package:finance_app/src/utils/input_formatter_tools.dart';
import 'package:finance_app/src/widgets/button/normal_button.dart';
import 'package:finance_app/src/widgets/button/normal_popup_button.dart';
import 'package:finance_app/src/widgets/button/normal_text_button.dart';
import 'package:finance_app/src/widgets/common/tag_widget.dart';
import 'package:finance_app/src/widgets/form/attach_file_form.dart';
import 'package:finance_app/src/widgets/form/buy_or_sell_form.dart';
import 'package:finance_app/src/widgets/form/form_edit_status_inherited_widget.dart';
import 'package:finance_app/src/widgets/form/text_area_input_form.dart';
import 'package:finance_app/src/widgets/form/value_select_form.dart';
import 'package:finance_app/src/widgets/common_app_bar.dart';
import 'package:finance_app/src/widgets/form/gst_inclusive_form.dart';
import 'package:finance_app/src/widgets/input/form_input_field.dart';
import 'package:finance_app/src/widgets/wrapper/normal_form_wrapper.dart';
import 'package:flutter/material.dart';
import 'package:finance_app/src/provider/dashboard/products_services/new_service_provider.dart';
import 'package:finance_app/src/router_gen/router_meta.dart';
import 'package:flutter/services.dart';
import 'package:tuple/tuple.dart';

@RouterMeta(paramName: "newServicePage")
class NewServicePage extends StatefulWidget {
  final bool isPro; // when the pro will need more information.
  final ServicesEntity data;
  final String text;

  const NewServicePage({Key key, this.isPro, this.data, this.text})
      : super(key: key);

  @override
  _NewServicePageState createState() => _NewServicePageState();
}

class _NewServicePageState extends State<NewServicePage>
    with PagePresenter<NewServicePage, NewServiceProvider> {
  String get title => provider.id == null
      ? S.current.new_service
      : provider.isEdit == true
          ? S.current.edit_service
          : S.current.service;

  Widget get rightButton => listBuilder<bool>(
        selector: (_, __) => __.isEdit == true || provider.id == null,
        builder: (BuildContext context, bool value, Widget child) =>
            value ? _buildSaveBtn() : _buildPopButton(),
      );

  @override
  PreferredSizeWidget get appBar => getDefaultAppBar(
          titleWidget: listBuilder<bool>(
            selector: (_, __) => __.isEdit,
            builder: (BuildContext context, bool value, Widget child) =>
                Text(title),
          ),
          actions: [
            if (widget.isPro == true) rightButton,
          ]);

  Widget _buildPopButton() => listBuilder<Tuple2<bool, int>>(
        selector: (_, __) => Tuple2(__.isEdit, __.menuList.length),
        builder:
            (BuildContext context, Tuple2<bool, int> value, Widget child) =>
                value.item1 == false
                    ? NormalMorePopupButton(
                        onSelect: provider.onSelectMenu,
                        menuList: provider.menuList,
                      )
                    : _buildSaveBtn(),
      );

  Widget _buildSaveBtn() {
    return NormalSaveTextButton(
      onTap: provider.onProSave,
    );
  }

  @override
  void initState() {
    provider.initService(widget.data, widget.text);
    super.initState();
  }

  @override
  Widget wrapperBody(Widget child) {
    return listBuilder<bool>(
      selector: (_, __) => __.isEdit == true || provider.id == null,
      builder: (BuildContext context, bool value, Widget child) =>
          FormEditStatusInheritedWidget(
        isEdit: value,
        child: child,
      ),
      child: child,
    );
  }

  @override
  Widget get buildWidget => ColoredBox(
        color: Colors.white,
        child: _buildProLayout(),
      );

  Widget _buildProLayout() => ListView(
        children: [
          Stack(
            children: [
              listBuilder<bool>(
                selector: (_, __) => __.numberHasError,
                builder: (BuildContext context, bool value, Widget child) =>
                    FromInputField(
                  tip: S.current.service_item_code,
                  controller: provider.codeController,
                  focusNode: provider.codeFocusNode,
                  hasError: value,
                ),
              ),
              Align(
                alignment: Alignment.centerRight,
                child: listBuilder<bool>(
                  selector: (_, __) => __.isActivate,
                  builder: (BuildContext context, bool value, Widget child) =>
                      value == false
                          ? Container(
                              margin: EdgeInsets.only(
                                  right: getDp(35), top: getDp(20)),
                              child: RedTagWidget(
                                content: S.current.deactivated,
                              ),
                            )
                          : Container(),
                ),
              )
            ],
          ),
          FromInputField(
            tip: S.current.service_name,
            controller: provider.nameController,
            focusNode: provider.nameFocusNode,
          ),
          listBuilder<String>(
            selector: (_, __) => __.categories?.join(','),
            builder: (BuildContext context, String value, Widget child) =>
                ValueSelectForm(
              title: S.current.categoryoptional,
              value: value,
              onTap: provider.onSelectCategory,
              border: null,
            ),
          ),
          listBuilder<bool>(
            selector: (_, __) => __.showSellPrice,
            builder: (BuildContext context, bool value, Widget child) =>
                value == true
                    ? Column(
                        children: [
                          AppSpaces.grayH6,
                          listBuilder<Tuple4<bool, String, String, bool>>(
                            selector: (_, __) =>
                                Tuple4<bool, String, String, bool>(
                                    __.isCheckSellInclusive,
                                    __.sellCurrency?.key,
                                    __.sellGstRate?.displayName,
                                    __.enableSell),
                            builder: (BuildContext context,
                                    Tuple4<bool, String, String, bool> value,
                                    Widget child) =>
                                BuyOrSellForm(
                              title: S.current.sell,
                              isCheckInclusive: value.item1,
                              unit: value.item2,
                              gstRate: value.item3,
                              isCheck: value.item4,
                              onChangeCheck: provider.onChangeSell,
                              onChangeCheckInclusive:
                                  provider.onChangeSellInclusive,
                              onChangeUnt: provider.onChangeSellUnit,
                              onChangeGstRate: provider.onChangeSellGstRate,
                              controller: provider.sellPriceController,
                              focusNode: provider.sellFocusNode,
                            ),
                          ),
                        ],
                      )
                    : Container(),
          ),
          listBuilder<bool>(
            selector: (_, __) => __.showBuyPrice,
            builder: (BuildContext context, bool value, Widget child) =>
                value == true
                    ? Column(
                        children: [
                          listBuilder<bool>(
                            selector: (_, __) => __.isEdit,
                            builder: (BuildContext context, bool value,
                                    Widget child) =>
                                value == null
                                    ? AppSpaces.grayH6
                                    : value
                                        ? AppSpaces.grayH6
                                        : AppSpaces.grayH05,
                          ),
                          listBuilder<Tuple4<bool, String, String, bool>>(
                            selector: (_, __) =>
                                Tuple4<bool, String, String, bool>(
                                    __.isCheckBuyInclusive,
                                    __.buyCurrency?.key,
                                    __.buyGstRate?.displayName,
                                    __.enableBuy),
                            builder: (BuildContext context,
                                    Tuple4<bool, String, String, bool> value,
                                    Widget child) =>
                                BuyOrSellForm(
                              title: S.current.buy,
                              isCheckInclusive: value.item1,
                              unit: value.item2,
                              gstRate: value.item3,
                              isCheck: value.item4,
                              onChangeCheck: provider.onChangeBuy,
                              onChangeCheckInclusive:
                                  provider.onChangeBuyInclusive,
                              onChangeUnt: provider.onChangeBuyUnit,
                              onChangeGstRate: provider.onChangeBuyGstRate,
                              controller: provider.buyPriceController,
                              focusNode: provider.buyFocusNode,
                            ),
                          ),
                        ],
                      )
                    : Container(),
          ),
          AppSpaces.grayH6,
          TextAreaInputForm(
            title: S.current.service_description_optional,
            controller: provider.serviceDescController,
            focusNode: provider.serviceDescFocusNode,
          ),
          NormalFormWrapper(
            child: listBuilder<Tuple2<List<String>, List<OcrAttachmentEntity>>>(
              selector: (_, __) =>
                  Tuple2(List.from(__.files), List.from(__.attachments ?? [])),
              builder: (BuildContext context,
                      Tuple2<List<String>, List<OcrAttachmentEntity>> value,
                      Widget child) =>
                  AttachFileForm(
                onAdd: provider.onAddAttachment,
                files: value.item1,
                onSelectFile: provider.onSelectFile,
                attachments: value.item2,
                onSelectAttachment: provider.onSelectAttachment,
              ),
            ),
          ),
        ],
      );
}
